package com.business.frame.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.business.base.BaseDao;
import com.business.base.Pager;
import com.business.frame.po.TableBean;
import com.common.NumberProcess;
import com.common.StringProcess;
import com.system.database.DS;

@Service("tableService")
@Transactional
public class TableService {

	private final String dbName = "frameDb";
	
	@Resource
	private BaseDao baseDao;
	
	private TableBean convert(Map<String, Object> model)
	{
		TableBean bean=new TableBean();
		
		bean.setTableId(StringProcess.convertToString(model.get("TableId")));
		bean.setTableName(StringProcess.convertToString(model.get("TableName")));
		bean.setTableText(StringProcess.convertToString(model.get("TableText")));
		bean.setDbName(StringProcess.convertToString(model.get("DbName")));
		bean.setTableName(StringProcess.convertToString(model.get("TableBackupName")));
		bean.setOrderNumber(NumberProcess.convertToNumber(model.get("OrderNumber")));
		
		return bean;
	}

	@DS(dbName)
	public String insert(Map<String, Object> model) {
		baseDao.save("frame.table.insert", model);

		return "";
	}

	@DS(dbName)
	public String delete(String tableId) {
		Map<String, Object> search = new HashMap<String, Object>();
		search.put("tableId", tableId);

		baseDao.save("frame.table.delete", search);

		return "";
	}

	@DS(dbName)
	public String update(Map<String, Object> model) {
		baseDao.save("frame.table.update", model);

		return "";
	}

	@DS(dbName)
	public Pager<Map<String, Object>> selectPage(int pageIndex, int pageSize, Map<String, Object> search) {

		Pager<Map<String, Object>> result = baseDao.selectListByPage(pageIndex, pageSize, "frame.table.select",search);
		
		for (int i = 0; i < result.getList().size(); i++) {
			Map<String, Object> item = result.getList().get(i);
			item.put("IndexNumber", (pageIndex - 1) * pageSize + i + 1);
		}
		
		return result;
	}

	@DS(dbName)
	public List<Map<String, Object>> select(Map<String, Object> search) {
		return baseDao.selectList("frame.table.select", search);
	}
	
	@DS(dbName)
	public TableBean getBeanByKeyId(String tableId)
	{
		Map<String, Object> search = new HashMap<String, Object>();
		search.put("tableId", tableId);
		List<Map<String, Object>> list=select(search);
		
		TableBean bean=null;
		if(list.size()>0)
		{
			bean=convert(list.get(0));
		}
		
		return bean;
	}

}
